# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/13
# @File   : R18_AdminPenalty_3Yr.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:3年内行政处罚校验
code:AdminPenalty_3Yr_2D
tableName:
columnName:
groups:准入>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import datetime
from dateutil.relativedelta import relativedelta
import re

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False



def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date



#行政处罚记录PAP [1,..1]    行政处罚记录信息单元PF04  [0..*]  行政处罚记录信息段  PF04A  [1..1]
#处罚金额 PF04AJ01  [1..1] 处罚生效日期 PF04AR01  [1..1]
def AdminPenalty_3Yr():
    data = IC_DSJ_2D['data']
    PAP = getTable(data, 'PAP', 1)
    if PAP is None:
        return u'缺失值'
    elif PAP == [{}] or PAP == "":
        return 0
    else:
        PF04 = getTable(PAP[0], 'PF04', 0)
        if PF04 is None or PF04 == "":
            return u'缺失值'
        elif PF04 == [{}]:
            return 0
        else:
            result = []
            for i in PF04:
                PF04A = getTable(i, 'PF04A', 1)
                if PF04A is None or PF04A == "":
                    result.append(None)
                else:
                    penalizeDate = PF04A[0].get('PF04AR01')
                    penalizeMoney = PF04A[0].get('PF04AJ01')
                    if Formate(penalizeDate) is not None and isfloat(penalizeMoney):
                        penalizeDateFormat = datetime.datetime.strptime(Formate(penalizeDate), '%Y-%m-%d')
                        today = datetime.datetime.now()
                        threeYearsAgo = datetime.datetime.now() - relativedelta(years=3)
                        if penalizeDateFormat > today:
                            result.append(None)
                            continue
                        if penalizeDateFormat > threeYearsAgo and float(penalizeMoney) > 1000:
                            result.append(1)
                        else:
                            result.append(0)
                    else:
                        result.append(None)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return u'缺失值'
            else:
                return sum(result)

result = AdminPenalty_3Yr()

